package com.mxpio.erp.plm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.mxpio.erp.common.enums.CommonEnums;
import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.enums.PlmEnums;
import com.mxpio.erp.common.enums.ProjectTaskEnums;
import com.mxpio.erp.common.plm.bo.ProjectProblemBO;
import com.mxpio.erp.common.plm.entity.*;
import com.mxpio.erp.common.plm.service.*;
import com.mxpio.erp.common.plm.vo.*;
import com.mxpioframework.camunda.service.BpmnFlowService;
import com.mxpioframework.common.exception.MBootException;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.JpaUtil;
import com.mxpioframework.jpa.lin.Linq;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import com.mxpioframework.jpa.query.SimpleCriterion;
import com.mxpioframework.security.entity.Dept;
import com.mxpioframework.security.util.SecurityUtils;
import com.mxpioframework.system.service.impl.BaseServiceImpl;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.feel.syntaxtree.If;
import org.checkerframework.checker.units.qual.A;
import org.hibernate.boot.model.source.internal.hbm.PluralAttributeElementSourceOneToManyImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ProjectInfoServiceImpl extends BaseServiceImpl<ProjectInfo> implements ProjectInfoService {
    @Autowired
    private ProjectInfoRecordDeliverableDraftService projectInfoRecordDeliverableDraftService;
    @Autowired
    private ProjectInfoRecordDraftService projectInfoRecordDraftService;

    @Autowired
    private BpmnFlowService bpmnFlowService;
    @Autowired
    private ProjectDeliverableService projectDeliverableService;

    @Autowired
    private ProjectInfoEndService projectInfoEndService;

    @Autowired
    private ProjectInfoStatusHistoryService projectInfoStatusHistoryService;

    @Autowired
    private ProjectInfoChangeRecordService projectInfoChangeRecordService;

    @Autowired
    private ProjectInfoApprovalService projectInfoApprovalService;

    @Autowired
    private ProjectInfoCompleteService projectInfoCompleteService;

    @Autowired
    private ProjectInfoChangeService projectInfoChangeService;

    @Autowired
    private ProjectInfoDraftServiceImpl projectInfoDraftService;

    @Autowired
    private ProjectTaskService projectTaskService;

    @Autowired
    private ProjectTaskDeliverableService projectTaskDeliverableService;

    @Autowired
    private ProjectDangerService projectDangerService;

    @Autowired
    private ProjectProblemService projectProblemService;

    @Autowired
    private ProjectInfoService projectInfoService;

    @Autowired
    private ProjectInfoTemplateService projectInfoTemplateService;

    @Autowired
    private ProjectDeliverableTemplateService projectDeliverableTemplateService;

    @Autowired
    private ProjectTaskDeliverableTemplateService projectTaskDeliverableTemplateService;

    @Autowired
    private ProjectTaskTemplateService projectTaskTemplateService;

    @Autowired
    private ProjectPauseOperationService projectPauseOperationService;

    @Autowired
    private ProjectRecoveryOperationService projectRecoveryOperationService;
    @Autowired
    private ProjectDeliverableDraftService projectDeliverableDraftService;
    @Autowired
    private ProjectInfoCompleteDeliverableDraftService projectInfoCompleteDeliverableDraftService;
    @Autowired
    private ProjectTaskMembersTimeService projectTaskMembersTimeService;


//    /**
//     * 分页查询 （一个字段中可能含有多个值）
//     * @param criteria
//     * @return
//     */
//    @Override
//    @Transactional
//    public List<ProjectInfo> list(Criteria criteria) {
//        List<Object> criterions = criteria.getCriterions();
//        boolean inFilterFlag = false;
//        String inFilterValue = "";
//        if (!criterions.isEmpty()){
//            Iterator<Object> iterator = criterions.iterator();
//            while(iterator.hasNext()){
//                Object next = iterator.next();
//                if (next instanceof SimpleCriterion){
//                    SimpleCriterion simpleCriterion = (SimpleCriterion) next;
//                    if (simpleCriterion.getFieldName().equals("proLeader")){
//                        inFilterFlag = true;
//                        inFilterValue = (String) simpleCriterion.getValue();
//                        iterator.remove();
//                        break;
//                    }
//                }
//            }
//        }
//        if (inFilterFlag){
//            Linq lin = JpaUtil.linq(ProjectInfo.class);
//            lin.and().add(lin.criteriaBuilder().gt(lin.criteriaBuilder().function("find_in_set", Integer.class, lin.criteriaBuilder().literal(inFilterValue), lin.root().get("proLeader")),0));
//            return (List<ProjectInfo>) lin.where(criteria);
//        }else{
//            return (List<ProjectInfo>) JpaUtil.linq(ProjectInfo.class).where(criteria);
//        }
//    }

    /**
     * 分页查询 （一个字段中可能含有多个值）
     *
     * @param page
     * @param criteria
     * @return
     */
    @Override
    @Transactional
    public Page<ProjectInfo> listPage(Pageable page, Criteria criteria) {
        List<Object> criterions = criteria.getCriterions();
        boolean inFilterFlag = false;
        String inFilterValue = "";
        if (!criterions.isEmpty()) {
            Iterator<Object> iterator = criterions.iterator();
            while (iterator.hasNext()) {
                Object next = iterator.next();
                if (next instanceof SimpleCriterion) {
                    SimpleCriterion simpleCriterion = (SimpleCriterion) next;
                    if (simpleCriterion.getFieldName().equals("proLeader")) {
                        inFilterFlag = true;
                        inFilterValue = (String) simpleCriterion.getValue();
                        iterator.remove();
                        break;
                    }
                }
            }
        }
        if (inFilterFlag) {
            Linq lin = JpaUtil.linq(ProjectInfo.class);
            lin.and().add(lin.criteriaBuilder().gt(lin.criteriaBuilder().function("find_in_set", Integer.class, lin.criteriaBuilder().literal(inFilterValue), lin.root().get("proLeader")), 0));
            return lin.where(criteria).paging(page);
        } else {
            return JpaUtil.linq(ProjectInfo.class).where(criteria).paging(page);
        }
    }

    /**
     * 终止项目-审批流程发起
     *
     * @param
     */
    @Override
    @Transactional
    public Result<?> end(String key, String loginUsername, String businessKey, Map<String, Object> properties) {
        String proCode = (String) properties.get("proCode");
        ProjectInfo projectInfo = this.getById(ProjectInfo.class, proCode);
        if (projectInfo == null) {
            return Result.error("项目不存在或项目状态不是执行中、已暂停");
        }
        if (!projectInfo.getProStatus().equals(PlmEnums.ProStatus.EXECUT.getCode()) && !projectInfo.getProStatus().equals(PlmEnums.ProStatus.PAUSE.getCode())) {
            return Result.error("项目状态不是执行中、已暂停");
        }
        //判断此时是否有其他的工作流在审核
        Criteria criteria = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode());
        List<ProjectInfoChange> list1 = projectInfoChangeService.list(ProjectInfoChange.class, criteria);
        for (ProjectInfoChange projectInfoChange : list1) {
            if (projectInfoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有变更工作流正在审核,不能终止");
            }
        }
        List<ProjectPauseOperation> list2 = projectPauseOperationService.list(ProjectPauseOperation.class, criteria);
        for (ProjectPauseOperation projectPauseOperation : list2) {
            if (projectPauseOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectPauseOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有暂停工作流在审核中,不能终止");
            }
        }
        List<ProjectRecoveryOperation> list3 = projectRecoveryOperationService.list(ProjectRecoveryOperation.class, criteria);
        for (ProjectRecoveryOperation projectRecoveryOperation : list3) {
            if (projectRecoveryOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectRecoveryOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有恢复工作流在审核中,不能终止");
            }
        }
        List<ProjectInfoComplete> list4 = projectInfoCompleteService.list(ProjectInfoComplete.class, criteria);
        for (ProjectInfoComplete projectInfoComplete : list4) {
            if (projectInfoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有结项工作流在审核中,不能终止");
            }
        }

        List<ProjectInfoEnd> list5 = projectInfoEndService.list(ProjectInfoEnd.class, criteria);
        for (ProjectInfoEnd projectInfoEnd : list5) {
            if (projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有终止工作流在审核中,不能重复提交");
            }
        }

        ProjectInfoEnd projectInfoEnd = new ProjectInfoEnd();
        projectInfoEnd.setProCode((String) properties.get("proCode"));
        projectInfoEnd.setChangeType((String) properties.get("changeType"));
        projectInfoEnd.setReason((String) properties.get("reason"));
        projectInfoEnd.setBpmnStatus(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode());
        projectInfoEnd.setApplicant(SecurityUtils.getLoginUsername());
        projectInfoEnd.setApplyTime(new Date());
//        projectInfoEnd.setIsAuditEnd(CommonEnums.YesNo.NO.getCode());//是否审核通过
        projectInfoEndService.save(projectInfoEnd);//存入终止申请单
        String bizNo = projectInfoEnd.getBizNo();
        properties.put("bizNo", bizNo);

        //将信息 存入草稿表
        ProjectInfoRecordDraft projectInfoRecordDraft = new ProjectInfoRecordDraft();
        BeanUtil.copyProperties(projectInfo, projectInfoRecordDraft);
        projectInfoRecordDraft.setBizNo(bizNo);
        projectInfoRecordDraftService.save(projectInfoRecordDraft);
        List<ProjectDeliverable> list = projectDeliverableService.list(ProjectDeliverable.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        for (ProjectDeliverable projectDeliverable : list){
            ProjectInfoRecordDeliverableDraft projectInfoRecordDeliverableDraft = new ProjectInfoRecordDeliverableDraft();
            BeanUtil.copyProperties(projectDeliverable, projectInfoRecordDeliverableDraft,"id");
            projectInfoRecordDeliverableDraft.setBizNo(bizNo);
            projectInfoRecordDeliverableDraftService.save(projectInfoRecordDeliverableDraft);
        }
        //发起工作流
        ProcessInstance processInstance = bpmnFlowService.startWithFormByKey(key, loginUsername, businessKey, properties);
        projectInfoEnd.setProcessInstanceId(processInstance.getId());
        projectInfoEndService.update(projectInfoEnd);
        return Result.OK(projectInfoEnd);
//        if (projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
//        //判断是新增单子，还是审批的单子
//        List<ProjectInfoEnd> infoEnds = projectInfoEndService.list(ProjectInfoEnd.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfoEnd.getProCode()));
//        for (ProjectInfoEnd end : infoEnds){
//            if (end.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())){
//                return Result.error("项目终止申请单还在审核,请先完成审核");
//            }
//        }
//        }
        //判断是否是新增的申请单
//        if (projectInfoEnd.getIsAuditEnd()==null){
//            projectInfoEnd.setApplicant(SecurityUtils.getLoginUsername());
//            projectInfoEnd.setApplyTime(new Date());
//            projectInfoEnd.setIsAuditEnd(CommonEnums.YesNo.NO.getCode());//是否审核通过
//            projectInfoEndService.save(projectInfoEnd);//存入终止申请单
//            return Result.OK(projectInfoEnd);
//        }

//        ProjectInfoEnd one = JpaUtil.linq(ProjectInfoEnd.class).equal("proCode", projectInfoEnd.getProCode()).findOne();
////        ProjectInfoEnd byId = projectInfoEndService.getById(ProjectInfoEnd.class, projectInfoEnd.getProCode());
//        if (one == null) {
//            projectInfoEnd.setApplicant(SecurityUtils.getLoginUsername());
//            projectInfoEnd.setApplyTime(new Date());
//            projectInfoEndService.save(projectInfoEnd);//存入终止申请单
//            return Result.OK(projectInfoEnd);
//        }else if (one.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())||
//                  one.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
//            return Result.error("项目终止申请单还在审核,请先完成审核");
//        }
//        //审核不通过时
//        if (projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CLOSED.getStatusCode())){
//            //删除申请表
//            projectInfoEndService.delete(ProjectInfoEnd.class, projectInfoEnd.getBizNo());
//            return Result.error("项目终止申请单还在审核,请先完成审核");
//        }
//        String proStatus = projectInfo.getProStatus();//取出变更前的状态
//        projectInfo.setProStatus(PlmEnums.ProStatus.END.getCode());//修改状态信息
//        this.update(projectInfo);
//
//        //对项目对应的任务中的项目状态进行更改
//        Criteria c = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode());
//        List<ProjectTask> list = projectTaskService.list(ProjectTask.class, c);
//        for (ProjectTask projectTask : list){
//            projectTask.setProStatus(projectInfo.getProStatus());
//            projectTaskService.update(projectTask);
//        }
//
//
//        String desc = PlmEnums.ProStatus.END.getDesc();
//        projectInfoStatusHistoryService.statusRecord(proStatus,projectInfo,desc);//存入状态记录
//        String remark = "项目终止";
//        projectInfoChangeRecordService.changeRecord(projectInfoEnd,remark);//存入变更记录
//        return Result.OK(projectInfo);
    }

    @Override
    @Transactional
    public Result<?> endOK(ProjectInfoEnd projectInfoEnd) {
        //审核通过
        if (projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())) {
            ProjectInfo projectInfo = this.getById(ProjectInfo.class, projectInfoEnd.getProCode());
            String proStatus = projectInfo.getProStatus();//取出变更前的状态
            projectInfo.setProStatus(PlmEnums.ProStatus.END.getCode());//修改状态信息
            this.update(projectInfo);
            //修改申请单信息
            List<ProjectInfoEnd> ends = projectInfoEndService.list(ProjectInfoEnd.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfoEnd.getProCode()));
            for (ProjectInfoEnd end : ends) {
                if (end.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())
                        ||end.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
                    end.setBpmnStatus(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode());
                    projectInfoEndService.update(end);
                }
            }

            //对项目对应的任务中的项目状态进行更改
            Criteria c = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode());
            List<ProjectTask> list = projectTaskService.list(ProjectTask.class, c);
            for (ProjectTask projectTask : list) {
                projectTask.setProStatus(projectInfo.getProStatus());
                projectTaskService.update(projectTask);
            }
            String desc = PlmEnums.ProStatus.END.getDesc();
            projectInfoStatusHistoryService.statusRecord(proStatus, projectInfo, desc);//存入状态记录
            String remark = "项目终止";
            projectInfoChangeRecordService.changeRecord(projectInfoEnd, remark);//存入变更记录
            return Result.OK(projectInfo);

            //审核未通过
        } else if (projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CLOSED.getStatusCode())) {
//            projectInfoEndService.update(projectInfoEnd);
            //修改申请单信息
            List<ProjectInfoEnd> ends = projectInfoEndService.list(ProjectInfoEnd.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfoEnd.getProCode()));
            for (ProjectInfoEnd end : ends) {
                if (end.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())
                        ||end.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())){
                    end.setBpmnStatus("不同意");
                    projectInfoEndService.update(end);
                }
            }
            return Result.OK("审核未通过");
        }
        return Result.error("流程审核状态不对");
    }




//    /**
//     * 立项
//     * @param projectInfo
//     */
//    @Override
//    @Transactional
//    public void approval(ProjectInfo projectInfo) {
//        ProjectInfo info = this.getById(ProjectInfo.class, projectInfo.getProCode());
//        if (info == null || info.getProStatus()!= PlmEnums.ProStatus.NEW.getCode()){
//            throw new MBootException("项目不存在或项目状态不是新增");
//        }
//        if (projectInfoApprovalService.getById(ProjectInfoApproval.class, projectInfo.getProCode()) !=null){
//            throw new MBootException("项目已有立项申请，请勿重复提交");
//        }
//        String proStatus = info.getProStatus();//取出变更前的状态
//        info.setProStatus(PlmEnums.ProStatus.EXECUT.getCode());//修改状态信息
//        this.update(info);
//        String desc = PlmEnums.ProStatus.EXECUT.getDesc();
//        projectInfoStatusHistoryService.statusRecord(proStatus,info,desc);//存入状态记录
//
//        //存入立项申请表
//        ProjectInfoApproval projectInfoApproval = new ProjectInfoApproval();
//        projectInfoApproval.setProCode(projectInfo.getProCode());
//        projectInfoApproval.setApplicant(SecurityUtils.getLoginUsername());
//        projectInfoApproval.setApplyTime(new Date());
//        projectInfoApproval.setBpmnStatus(PlmEnums.BpmnStatus.CREATE.getCode());
//        projectInfoApprovalService.save(projectInfoApproval);
//    }

    /**
     * 立项审核
     *
     * @param
     */
    @Override
    @Transactional
    public Result<?> approvalOK(String key, String loginUsername, String businessKey, Map<String, Object> properties) {
        String proCode = (String) properties.get("proCode");
        ProjectInfo info = this.getById(ProjectInfo.class, proCode);
        if (info == null || !info.getProStatus().equals(PlmEnums.ProStatus.NEW.getCode())) {
            return Result.error("项目不存在或状态不是新增");
        }
        Criteria criteria = Criteria.create().addCriterion("proCode", Operator.EQ, proCode);
        List<ProjectInfoApproval> list1 = projectInfoApprovalService.list(ProjectInfoApproval.class, criteria);
        for (ProjectInfoApproval ProjectInfoApproval : list1) {
            if (ProjectInfoApproval.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    ProjectInfoApproval.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有立项工作流在审核中,不能重复提交");
            }
        }
            ProjectInfoApproval projectInfoApproval = new ProjectInfoApproval();
            projectInfoApproval.setProCode(proCode);
            projectInfoApproval.setApplicant(SecurityUtils.getLoginUsername());
            projectInfoApproval.setApplyTime(new Date());
            projectInfoApproval.setBpmnStatus(PlmEnums.BpmnStatus.CREATE.getCode());
            projectInfoApprovalService.save(projectInfoApproval);
            String bizNo = projectInfoApproval.getBizNo();
            properties.put("bizNo", bizNo);

            //将信息 存入草稿表
        ProjectInfoRecordDraft projectInfoRecordDraft = new ProjectInfoRecordDraft();
        BeanUtil.copyProperties(info, projectInfoRecordDraft);
        projectInfoRecordDraft.setBizNo(bizNo);
        projectInfoRecordDraftService.save(projectInfoRecordDraft);
        List<ProjectDeliverable> list = projectDeliverableService.list(ProjectDeliverable.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        for (ProjectDeliverable projectDeliverable : list){
            ProjectInfoRecordDeliverableDraft projectInfoRecordDeliverableDraft = new ProjectInfoRecordDeliverableDraft();
            BeanUtil.copyProperties(projectDeliverable, projectInfoRecordDeliverableDraft,"id");
            projectInfoRecordDeliverableDraft.setBizNo(bizNo);
            projectInfoRecordDeliverableDraftService.save(projectInfoRecordDeliverableDraft);
        }



        //发起工作流
            ProcessInstance processInstance = bpmnFlowService.startWithFormByKey(key, loginUsername, businessKey, properties);
            projectInfoApproval.setProcessInstanceId(processInstance.getId());
            projectInfoApprovalService.update(projectInfoApproval);
            return Result.OK(projectInfoApproval);
    }

    /**
     * 立项审核结果
     *
     * @param
     * @return
     */
    @Override
    @Transactional
    public Result<?> approvalSuccess(ProjectInfo projectInfo) {
        ProjectInfo info = this.getById(ProjectInfo.class, projectInfo.getProCode());
        String proStatus = info.getProStatus();//取出变更前的状态
        String bpmnStatus = projectInfo.getBpmnStatus();
        //审核不通过
        if (bpmnStatus.equals(OrderStatusEnums.BpmnStatus.CLOSED.getStatusCode())) {
//            info.setProStatus(PlmEnums.ProStatus.NEW.getCode());
//            this.update(info);
            //修改申请单状态
            List<ProjectInfoApproval> completes = projectInfoApprovalService.list(ProjectInfoApproval.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoApproval infoApproval : completes){
                if (infoApproval.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                        ||infoApproval.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
                    infoApproval.setBpmnStatus("不同意");
                    projectInfoApprovalService.update(infoApproval);
                }
            }
            String desc = "项目审核不同意";
            projectInfoStatusHistoryService.statusRecord(proStatus, info, desc);//存入状态记录
           return Result.OK("审核不通过");
        }
//        if (bpmnStatus.equals(PlmEnums.BpmnStatus.NOAGREE.getCode())) {
//            info.setProStatus(PlmEnums.ProStatus.END.getCode());
//            this.update(info);
//            //修改申请单状态
//            List<ProjectInfoApproval> completes = projectInfoApprovalService.list(ProjectInfoApproval.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
//            for (ProjectInfoApproval infoApproval : completes){
//                if (infoApproval.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
//                        ||infoApproval.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
//                    infoApproval.setBpmnStatus(projectInfo.getBpmnStatus());
//                    projectInfoApprovalService.update(infoApproval);
//                }
//            }
//            //对项目对应的任务中的项目状态进行更改
//            Criteria criteria = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode());
//            List<ProjectTask> list = projectTaskService.list(ProjectTask.class, criteria);
//            for (ProjectTask projectTask : list) {
//                projectTask.setProStatus(info.getProStatus());
//                projectTaskService.update(projectTask);
//            }
//
//            String desc = "项目未通过审核";
//            projectInfoStatusHistoryService.statusRecord(proStatus, info, desc);//存入状态记录
//            return Result.error("项目未通过审核,状态改已终止");
//        }
        //此时审核状态为同意
        if (bpmnStatus.equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())) {
            info.setProStatus(PlmEnums.ProStatus.EXECUT.getCode());
            info.setActualStartTime(new Date());
            BigDecimal zero = BigDecimal.ZERO;
            info.setSchedule(zero);//设置项目进度
            this.update(info);//更新项目状态
            //修改申请单状态
            List<ProjectInfoApproval> completes = projectInfoApprovalService.list(ProjectInfoApproval.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoApproval infoApproval : completes){
                if (infoApproval.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                        ||infoApproval.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
                    infoApproval.setBpmnStatus(projectInfo.getBpmnStatus());
                    projectInfoApprovalService.update(infoApproval);
                }
            }

            //对项目对应的任务中的项目状态进行更改
            Criteria criteria = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode());
            List<ProjectTask> list = projectTaskService.list(ProjectTask.class, criteria);
            for (ProjectTask projectTask : list) {
                projectTask.setProStatus(info.getProStatus());
                projectTaskService.update(projectTask);
            }

            String desc = PlmEnums.ProStatus.EXECUT.getDesc();
            projectInfoStatusHistoryService.statusRecord(proStatus, info, desc);//存入状态记录
            return Result.OK(info);
        }
        return Result.error("项目状态异常");
    }

    /**
     * 项目结项
     *
     * @param
     */
    @Override
    @Transactional
    @SuppressWarnings("unchecked")
    public Result<?> complete(String key, String loginUsername, String businessKey, Map<String, Object> properties) {
        String proCode = (String) properties.get("proCode");
        ProjectInfo projectInfo = this.getById(ProjectInfo.class, proCode);
        if (projectInfo == null || !projectInfo.getProStatus().equals(PlmEnums.ProStatus.EXECUT.getCode())) {
            return Result.error("项目不存在或者项目状态不是执行中,不能结项");
        }
        //当项目进度没有100时，不可以结项
        if (projectInfo.getSchedule().compareTo(BigDecimal.valueOf(100)) != 0) {
            return Result.error("项目进度没有达到100%,不能结项");
        }
        //判断此时是否有其他的工作流在审核
        Criteria criteria = Criteria.create().addCriterion("proCode", Operator.EQ, proCode);
        List<ProjectInfoChange> list = projectInfoChangeService.list(ProjectInfoChange.class, criteria);
        for (ProjectInfoChange projectInfoChange : list) {
            if (projectInfoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有变更工作流在审核中,不能结项");
            }
        }
        List<ProjectInfoEnd> list1 = projectInfoEndService.list(ProjectInfoEnd.class, criteria);
        for (ProjectInfoEnd projectInfoEnd : list1) {
            if (projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有终止工作流在审核中,不能结项");
            }
        }
        List<ProjectPauseOperation> list2 = projectPauseOperationService.list(ProjectPauseOperation.class, criteria);
        for (ProjectPauseOperation projectPauseOperation : list2) {
            if (projectPauseOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectPauseOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有暂停工作流在审核中,不能结项");
            }
        }
        List<ProjectRecoveryOperation> list3 = projectRecoveryOperationService.list(ProjectRecoveryOperation.class, criteria);
        for (ProjectRecoveryOperation projectRecoveryOperation : list3) {
            if (projectRecoveryOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectRecoveryOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有恢复工作流在审核中,不能结项");
            }
        }

        List<ProjectInfoComplete> list4 = projectInfoCompleteService.list(ProjectInfoComplete.class, criteria);
        for (ProjectInfoComplete projectInfoComplete : list4) {
            if (projectInfoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有结项工作流在审核中,不能重复提交");
            }
        }

        ProjectInfoComplete infoComplete = new ProjectInfoComplete();
        infoComplete.setProCode(proCode);
        infoComplete.setConIllustrate((String) properties.get("conIllustrate"));
        infoComplete.setBpmnStatus(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode());
        infoComplete.setApplicant(SecurityUtils.getLoginUsername());
        infoComplete.setApplyTime(new Date());
        projectInfoCompleteService.save(infoComplete);
        String bizNo = infoComplete.getBizNo();
        properties.put("bizNo", bizNo);

        //将信息 存入草稿表
        ProjectInfoRecordDraft projectInfoRecordDraft = new ProjectInfoRecordDraft();
        BeanUtil.copyProperties(projectInfo, projectInfoRecordDraft);
        projectInfoRecordDraft.setBizNo(bizNo);
        projectInfoRecordDraftService.save(projectInfoRecordDraft);
//        List<ProjectDeliverable> list = projectDeliverableService.list(ProjectDeliverable.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
//        for (ProjectDeliverable projectDeliverable : list){
//            ProjectInfoRecordDeliverableDraft projectInfoRecordDeliverableDraft = new ProjectInfoRecordDeliverableDraft();
//            BeanUtil.copyProperties(projectDeliverable, projectInfoRecordDeliverableDraft);
//            projectInfoRecordDeliverableDraft.setBizNo(bizNo);
//            projectInfoRecordDeliverableDraftService.save(projectInfoRecordDeliverableDraft);
//        }
        //发起工作流
        ProcessInstance processInstance = bpmnFlowService.startWithFormByKey(key, loginUsername, businessKey, properties);
        infoComplete.setProcessInstanceId(processInstance.getId());
        projectInfoCompleteService.update(infoComplete);
        //将交付物存入草稿表中
        List<LinkedHashMap<String, Object>> deliverables = (List<LinkedHashMap<String, Object>>) properties.get("deliverables");
        for (LinkedHashMap<String, Object> map : deliverables){
            ProjectInfoCompleteDeliverableDraft projectInfoCompleteDeliverableDraft = new ProjectInfoCompleteDeliverableDraft();
            projectInfoCompleteDeliverableDraft.setProCode(proCode);
            projectInfoCompleteDeliverableDraft.setDocNO(map.get("docNO").toString());
            projectInfoCompleteDeliverableDraft.setDocName(map.get("docName").toString());
            projectInfoCompleteDeliverableDraft.setDocType(map.get("docType").toString());
            projectInfoCompleteDeliverableDraft.setDocTemp(map.get("docTemp") != null ? map.get("docTemp").toString() : null);
            projectInfoCompleteDeliverableDraft.setDocFile(map.get("docFile") != null ?map.get("docFile").toString():null);
            projectInfoCompleteDeliverableDraft.setNumber(map.get("number") != null ? Integer.parseInt(map.get("number").toString()):null);
            projectInfoCompleteDeliverableDraft.setIsAuditEnd(CommonEnums.YesNo.NO.getCode());
            projectInfoCompleteDeliverableDraft.setBizNo(infoComplete.getBizNo());
            projectInfoCompleteDeliverableDraftService.save(projectInfoCompleteDeliverableDraft);
        }
        return Result.OK(infoComplete);


    }

    @Override
    @Transactional
    public Result<?> completeOK(ProjectInfoComplete projectInfoComplete) {
        //审核通过
        if (projectInfoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())) {
            ProjectInfo projectInfo = this.getById(ProjectInfo.class,projectInfoComplete.getProCode());
            String proStatus = projectInfo.getProStatus();//取出变更前的状态
            projectInfo.setProStatus(PlmEnums.ProStatus.FINISH.getCode());//修改状态信息
            //判断项目是否逾期
            LocalDate currentDate = LocalDate.now(); //获取当前时间
            Date planEndTime = projectInfo.getPlanEndTime();
            LocalDate planEndLocalDate = planEndTime.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            if (currentDate.isAfter(planEndLocalDate)) {
                projectInfo.setStatus("0");//当计划时间超过当前时间时，判断为当前项目延期
            }
            projectInfo.setActualEndTime(new Date());
            this.update(projectInfo);
            //修改申请单状态
            List<ProjectInfoComplete> completes = projectInfoCompleteService.list(ProjectInfoComplete.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoComplete infoComplete : completes){
                if (infoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                        ||infoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
                    infoComplete.setBpmnStatus(projectInfoComplete.getBpmnStatus());
                    projectInfoCompleteService.update(infoComplete);
                }
            }
            //存入项目交付物
            List<ProjectInfoCompleteDeliverableDraft> deliverableDrafts = projectInfoCompleteDeliverableDraftService.list(ProjectInfoCompleteDeliverableDraft.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoCompleteDeliverableDraft projectInfoCompleteDeliverableDraft : deliverableDrafts) {
                if(projectInfoCompleteDeliverableDraft.getIsAuditEnd()==null||projectInfoCompleteDeliverableDraft.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())){
                    ProjectDeliverable deliverable = JpaUtil.linq(ProjectDeliverable.class).equal("docNO", projectInfoCompleteDeliverableDraft.getDocNO()).findOne();
                    deliverable.setDocFile(projectInfoCompleteDeliverableDraft.getDocFile());
                    projectDeliverableService.update(deliverable);
                    projectInfoCompleteDeliverableDraft.setIsAuditEnd(CommonEnums.YesNo.YES.getCode());//改为审核结束
                    projectInfoCompleteDeliverableDraftService.update(projectInfoCompleteDeliverableDraft);
                }
            }


            //对项目对应的任务中的项目状态进行更改
            Criteria c = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode());
            List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, c);
            for (ProjectTask projectTask : tasks) {
                projectTask.setProStatus(projectInfo.getProStatus());
                projectTaskService.update(projectTask);
            }

            String desc = PlmEnums.ProStatus.FINISH.getDesc();
            projectInfoStatusHistoryService.statusRecord(proStatus, projectInfo, desc);//存入状态记录
            return Result.OK(projectInfo);

            //审核不通过
        } else if (projectInfoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CLOSED.getStatusCode())) {
            ProjectInfo projectInfo = this.getById(ProjectInfo.class,projectInfoComplete.getProCode());
            String proStatus = projectInfo.getProStatus();//取出变更前的状态
            String desc = "审核不通过";
            projectInfoStatusHistoryService.statusRecord(proStatus, projectInfo, desc);//存入状态记录
            //修改申请单状态
            List<ProjectInfoComplete> completes = projectInfoCompleteService.list(ProjectInfoComplete.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoComplete infoComplete : completes){
                if (infoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                        ||infoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
                    infoComplete.setBpmnStatus("不同意");
                    projectInfoCompleteService.update(infoComplete);
                }
            }
            //修改项目结项交付物草稿表
            List<ProjectInfoCompleteDeliverableDraft> deliverableDrafts = projectInfoCompleteDeliverableDraftService.list(ProjectInfoCompleteDeliverableDraft.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoCompleteDeliverableDraft projectInfoCompleteDeliverableDraft : deliverableDrafts) {
                if (projectInfoCompleteDeliverableDraft.getIsAuditEnd()==null || projectInfoCompleteDeliverableDraft.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())){
                    projectInfoCompleteDeliverableDraft.setIsAuditEnd(CommonEnums.YesNo.YES.getCode());
                    projectInfoCompleteDeliverableDraftService.update(projectInfoCompleteDeliverableDraft);
                }
            }
            return Result.OK("完工申请审核未通过");

        }
        return Result.error("审核状态不对");
    }



    /**
     * 变更项目
     *
     * @param
     */
    @Override
    @Transactional
    public Result<?> change(String key, String loginUsername, String businessKey, Map<String, Object> properties) {
        String proCode = properties.get("proCode").toString();
        ProjectInfo bean = this.getById(ProjectInfo.class, proCode);
        if (bean == null) {
            return Result.error("项目不存在");
        }
        if (!bean.getProStatus().equals(PlmEnums.ProStatus.EXECUT.getCode()) && !bean.getProStatus().equals(PlmEnums.ProStatus.PAUSE.getCode())) {
            return Result.error("状态不是执行中、已暂停不能变更");
        }
        //判断此时是否有其他的工作流在审核
        Criteria criteria = Criteria.create().addCriterion("proCode", Operator.EQ, proCode);
        List<ProjectInfoEnd> list1 = projectInfoEndService.list(ProjectInfoEnd.class, criteria);
        for (ProjectInfoEnd projectInfoEnd : list1) {
            if (projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoEnd.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有终止工作流在审核中,不能变更");
            }
        }
        List<ProjectPauseOperation> list2 = projectPauseOperationService.list(ProjectPauseOperation.class, criteria);
        for (ProjectPauseOperation projectPauseOperation : list2) {
            if (projectPauseOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectPauseOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有暂停工作流在审核中,不能变更");
            }
        }
        List<ProjectRecoveryOperation> list3 = projectRecoveryOperationService.list(ProjectRecoveryOperation.class, criteria);
        for (ProjectRecoveryOperation projectRecoveryOperation : list3) {
            if (projectRecoveryOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectRecoveryOperation.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有恢复工作流在审核中,不能变更");
            }
        }
        List<ProjectInfoComplete> list4 = projectInfoCompleteService.list(ProjectInfoComplete.class, criteria);
        for (ProjectInfoComplete projectInfoComplete : list4) {
            if (projectInfoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoComplete.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有结项工作流在审核中,不能变更");
            }
        }
        List<ProjectInfoChange> list = projectInfoChangeService.list(ProjectInfoChange.class, criteria);
        for (ProjectInfoChange projectInfoChange : list) {
            if (projectInfoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode()) ||
                    projectInfoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())) {
                return Result.error("项目有变更工作流在审核中,不能重复提交");
            }
        }
        ProjectInfoChange projectInfoChange = new ProjectInfoChange();
        projectInfoChange.setProCode(proCode);
        projectInfoChange.setApplicant(SecurityUtils.getLoginUsername());
        projectInfoChange.setApplyTime(new Date());
        projectInfoChange.setChangeType("5");
        projectInfoChange.setReason(properties.get("reason").toString());
        projectInfoChange.setBpmnStatus(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode());
        projectInfoChangeService.save(projectInfoChange);//添加项目变更单
        String bizNo = projectInfoChange.getBizNo();
        properties.put("bizNo", bizNo);

        //发起工作流
        ProcessInstance processInstance = bpmnFlowService.startWithFormByKey(key, loginUsername, businessKey, properties);
        projectInfoChange.setProcessInstanceId(processInstance.getId());
        projectInfoChangeService.update(projectInfoChange);
        //将将要变更的项目信息放在草稿表中
        ProjectInfo projectInfo = new ProjectInfo();
        projectInfo.setInfoDeptId(properties.get("infoDeptId").toString());
        projectInfo.setProCode(proCode);
        projectInfo.setProName(properties.get("proName").toString());
        projectInfo.setStatus(properties.get("status").toString());
        projectInfo.setSchedule(new BigDecimal(properties.get("schedule").toString()));
        projectInfo.setProStatus(properties.get("proStatus").toString());
        projectInfo.setPriority(properties.get("priority").toString());
        projectInfo.setProSource(properties.get("proSource").toString());
        projectInfo.setProType(properties.get("proType").toString());
        projectInfo.setProLeader(properties.get("proLeader").toString());
        projectInfo.setProSecretary(properties.get("proSecretary") != null ? properties.get("proSecretary").toString() : null);
        //string类型转化为Date类型
        String dateStr =(String) properties.get("planStartTime");
        if (dateStr != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(dateStr, formatter);
            Date oldDate = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
            projectInfo.setPlanStartTime(oldDate);
        }
        //string类型转化为Date类型
        String dateStr1 =(String) properties.get("planEndTime");
        if (dateStr1 != null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate date = LocalDate.parse(dateStr1, formatter);
            Date oldDate = Date.from(date.atStartOfDay(ZoneId.systemDefault()).toInstant());
            projectInfo.setPlanEndTime(oldDate);
        }
        projectInfo.setDuration(new BigDecimal(properties.get("duration").toString()));
        projectInfo.setProBudget(properties.get("proBudget") != null ? new BigDecimal(properties.get("proBudget").toString()) : null);
        projectInfo.setProRange(properties.get("proRange") != null ? properties.get("proRange").toString() : null);
        projectInfo.setProTarget(properties.get("proTarget") != null ? properties.get("proTarget").toString() : null);
        projectInfo.setRules(properties.get("rules") != null ? properties.get("rules").toString() : null);
        projectInfo.setIsTemplate(properties.get("isTemplate") != null ? properties.get("isTemplate").toString() : null);
        projectInfoDraftService.saveDraft(projectInfo,projectInfoChange);
        //将要变更的交付物放在草稿表中
        //若项目本身含有交付物不动，需要取出，共同放置交付物草稿表
        List<ProjectDeliverable> list5 = projectDeliverableService.list(ProjectDeliverable.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        List<LinkedHashMap<String, Object>> deliverables = (List<LinkedHashMap<String, Object>>) properties.get("projectDeliverable");
        String docNOs = null;
        if (deliverables!=null){
        for (LinkedHashMap<String, Object> map : deliverables){
            ProjectDeliverableDraft projectDeliverableDraft = new ProjectDeliverableDraft();
            projectDeliverableDraft.setProCode(proCode);
            projectDeliverableDraft.setBizNo(bizNo);
            if (map.get("crudType").toString().equals("SAVE")){
                projectDeliverableDraft.setDocName(map.get("docName").toString());
                projectDeliverableDraft.setDocType(map.get("docType").toString());
                projectDeliverableDraft.setDocTemp(map.get("docTemp") != null ? map.get("docTemp").toString() : null);
                projectDeliverableDraft.setDocFile(map.get("docFile") != null ?map.get("docFile").toString():null);
                projectDeliverableDraft.setNumber(map.get("number") != null ? Integer.parseInt(map.get("number").toString()): null);
                projectDeliverableDraft.setIsAuditEnd(CommonEnums.YesNo.NO.getCode());
                projectDeliverableDraftService.save(projectDeliverableDraft);
            }else if (!map.get("crudType").toString().equals("DELETE")){
                if (docNOs == null){
                    docNOs = map.get("docNO").toString();
                }else {
                    docNOs = docNOs + ","+map.get("docNO").toString();
                }
//                projectDeliverableDraft.setDocNO(map.get("docNO").toString());
                projectDeliverableDraft.setDocName(map.get("docName").toString());
                projectDeliverableDraft.setDocType(map.get("docType").toString());
                projectDeliverableDraft.setDocTemp(map.get("docTemp") != null ? map.get("docTemp").toString() : null);
                projectDeliverableDraft.setDocFile(map.get("docFile") != null ?map.get("docFile").toString():null);
                projectDeliverableDraft.setNumber(map.get("number") != null ? Integer.parseInt(map.get("number").toString()): null);
                projectDeliverableDraft.setIsAuditEnd(CommonEnums.YesNo.NO.getCode());
                projectDeliverableDraftService.save(projectDeliverableDraft);
            }
            if (map.get("crudType").toString().equals("DELETE")){
                if (docNOs == null){
                    docNOs = map.get("docNO").toString();
                }else {
                    docNOs = docNOs + ","+map.get("docNO").toString();
                }
            }
        }
        }
        for (ProjectDeliverable projectDeliverable : list5){
            String docNO = projectDeliverable.getDocNO();
            if (docNOs!=null){
                boolean isNotInDocNOs = isContainedInDocNOs(docNOs, docNO);
                if (isNotInDocNOs == false ){
                    ProjectDeliverableDraft projectDeliverableDraft = new ProjectDeliverableDraft();
                    projectDeliverableDraft.setBizNo(bizNo);
                    projectDeliverableDraft.setDocNO(projectDeliverable.getDocNO());
                    projectDeliverableDraft.setProCode(proCode);
                    projectDeliverableDraft.setDocName(projectDeliverable.getDocName());
                    projectDeliverableDraft.setDocType(projectDeliverable.getDocType());
                    projectDeliverableDraft.setDocTemp(projectDeliverable.getDocTemp());
                    projectDeliverableDraft.setDocFile(projectDeliverable.getDocTemp());
                    projectDeliverableDraft.setNumber(projectDeliverable.getNumber());
                    projectDeliverableDraft.setIsAuditEnd(CommonEnums.YesNo.NO.getCode());
                    projectDeliverableDraftService.save(projectDeliverableDraft);
                }
            }else {
                ProjectDeliverableDraft projectDeliverableDraft = new ProjectDeliverableDraft();
                projectDeliverableDraft.setBizNo(bizNo);
                projectDeliverableDraft.setProCode(proCode);
                projectDeliverableDraft.setDocNO(projectDeliverable.getDocNO());
                projectDeliverableDraft.setDocName(projectDeliverable.getDocName());
                projectDeliverableDraft.setDocType(projectDeliverable.getDocType());
                projectDeliverableDraft.setDocTemp(projectDeliverable.getDocTemp());
                projectDeliverableDraft.setDocFile(projectDeliverable.getDocTemp());
                projectDeliverableDraft.setNumber(projectDeliverable.getNumber());
                projectDeliverableDraft.setIsAuditEnd(CommonEnums.YesNo.NO.getCode());
                projectDeliverableDraftService.save(projectDeliverableDraft);
            }
        }

        return Result.OK(projectInfoChange);
    }


    // 辅助方法：检查docNO是否在docNOs列表中
    public static boolean isContainedInDocNOs(String docNOs, String docNO) {
        // 使用split方法按逗号分割字符串
        String[] docNOsArray = docNOs.split(",");

        // 遍历数组检查docNO
        for (String s : docNOsArray) {
            // 去除可能的空格并比较
            if (s.trim().equals(docNO)) {
                return true; // 如果找到匹配项，返回true
            }
        }

        // 如果没有找到匹配项，返回false
        return false;
    }

    /**
     * 变更单审核通过
     *
     * @param projectInfoChange
     */
    @Override
    @Transactional
    public Result<?> changeOK(ProjectInfoChange projectInfoChange) {
        ProjectInfo projectInfo = this.getById(ProjectInfo.class, projectInfoChange.getProCode());
        if (projectInfo == null) {
            return Result.error("项目不存在或者状态不是执行中、已暂停不能变更");
        }
        if (!projectInfo.getProStatus().equals(PlmEnums.ProStatus.EXECUT.getCode())
                && !projectInfo.getProStatus().equals(PlmEnums.ProStatus.PAUSE.getCode())) {
            return Result.error("状态不是执行中、已暂停不能变更");
        }
//        ProjectInfoChange one = JpaUtil.linq(ProjectInfoChange.class).equal("proCode", projectInfoChange.getProCode()).findOne();
////        ProjectInfoChange byId = projectInfoChangeService.getById(ProjectInfoChange.class, projectInfoChange.getProCode());
//        if (one == null){
//            return Result.error("项目变更单不存在");
//            }
        if (projectInfoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITED.getStatusCode())) {
            Criteria criteria1 = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfoChange.getProCode());
            List<ProjectInfoDraft> list1 = projectInfoDraftService.list(ProjectInfoDraft.class, criteria1);//取出草稿表里面的数据
            for (ProjectInfoDraft draft : list1) {
                if(draft.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())||draft.getIsAuditEnd()==null){
                    projectInfo.setProName(draft.getProName());
                    projectInfo.setStatus(draft.getStatus());
                    projectInfo.setSchedule(draft.getSchedule());
                    projectInfo.setPriority(draft.getPriority());
                    projectInfo.setProSource(draft.getProSource());
                    projectInfo.setProType(draft.getProType());
                    projectInfo.setProLeader(draft.getProLeader());
                    projectInfo.setProSecretary(draft.getProSecretary());
                    projectInfo.setPlanStartTime(draft.getPlanStartTime());
                    projectInfo.setPlanEndTime(draft.getPlanEndTime());
                    projectInfo.setDuration(draft.getDuration());
                    projectInfo.setProBudget(draft.getProBudget());
                    projectInfo.setProRange(draft.getProRange());
                    projectInfo.setProTarget(draft.getProTarget());
                    projectInfo.setRules(draft.getRules());
                    projectInfo.setIsTemplate(draft.getIsTemplate());
                    projectInfo.setInfoDeptId(draft.getInfoDeptId());
                    this.update(projectInfo);//变更项目信息
                }
            }

            //对项目对应的任务中的项目状态和项目名称和项目经理进行更改
            Criteria c = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode());
            List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, c);
            for (ProjectTask projectTask : tasks) {
                projectTask.setProStatus(projectInfo.getProStatus());
                projectTask.setProName(projectInfo.getProName());
                projectTask.setProLeader(projectInfo.getProLeader());
                projectTaskService.update(projectTask);
            }

            //查找草稿表交付物
            Criteria criteria = Criteria.create().addCriterion("proCode", Operator.EQ, projectInfoChange.getProCode());
            projectDeliverableService.deleteBatch(ProjectDeliverable.class, criteria);//删除原先的项目交付物
            List<ProjectDeliverableDraft> list = projectDeliverableDraftService.list(ProjectDeliverableDraft.class, criteria);//查找草稿表交付
            for (ProjectDeliverableDraft draft1 : list) {
                if (draft1.getIsAuditEnd()==null||draft1.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())){
                    ProjectDeliverable deliverable = new ProjectDeliverable();
                    BeanUtil.copyProperties(draft1, deliverable, "id");
                    projectDeliverableService.save(deliverable);
                }
            }

            //修改申请单状态
            List<ProjectInfoChange> completes = projectInfoChangeService.list(ProjectInfoChange.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoChange infoChange : completes){
                if (infoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                        ||infoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
                    infoChange.setBpmnStatus(projectInfoChange.getBpmnStatus());
                    projectInfoChangeService.update(infoChange);
                }
            }
            //修改草稿表的状态
            List<ProjectInfoDraft> drafts = projectInfoDraftService.list(ProjectInfoDraft.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoDraft infoDraft : drafts){
                if (infoDraft.getIsAuditEnd()==null|| infoDraft.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())){
                    infoDraft.setIsAuditEnd(CommonEnums.YesNo.YES.getCode());
                    projectInfoDraftService.update(infoDraft);
                }
            }
            //修改草稿表-交付物的状态
            List<ProjectDeliverableDraft> deliverableDrafts = projectDeliverableDraftService.list(ProjectDeliverableDraft.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectDeliverableDraft deliverableDraft : deliverableDrafts){
                if (deliverableDraft.getIsAuditEnd()==null|| deliverableDraft.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())){
                    deliverableDraft.setIsAuditEnd(CommonEnums.YesNo.YES.getCode());
                    projectDeliverableDraftService.update(deliverableDraft);
                }
            }

//            this.save(projectInfo, new SmartCrudPolicyAdapter() {
//                @Override
//                public boolean beforeInsert(CrudContext context){
//                    Object o = context.getEntity();
//                    if (o instanceof ProjectDeliverable){
//                        ProjectInfo info = context.getParent();
//                        ((ProjectDeliverable) o).setProCode(info.getProCode());
//                    }
//                    return  true;
//                }
//            });


//            List<ProjectDeliverableDraft> list = projectDeliverableDraftService.list(ProjectDeliverableDraft.class,
//                    Criteria.create().addCriterion("proCode",Operator.EQ,projectInfoChange.getProCode()));
//            for (ProjectDeliverableDraft deliverableDraft : list ){
//                if (deliverableDraft.getDocNO()==null){
//                    ProjectDeliverable deliverable = new ProjectDeliverable();
//                    BeanUtil.copyProperties(deliverableDraft,deliverable);
//                    projectDeliverableService.save(deliverable)
//                }
//            }
//            //将草稿表的信息删除
//            projectInfoDraftService.delete(ProjectInfoDraft.class, projectInfoChange.getProCode());
//            projectDeliverableDraftService.deleteBatch(ProjectDeliverableDraft.class,
//                    Criteria.create().addCriterion("proCode", Operator.EQ, projectInfoChange.getProCode()));

            //存入变更记录
            String remark = "变更内容";
            projectInfoChangeRecordService.changeRecordSubstance(projectInfoChange, remark);
            return Result.OK("projectInfo");
        }
        if (projectInfoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CLOSED.getStatusCode())) {
//            //将草稿表的信息删除
//            projectInfoDraftService.delete(ProjectInfoDraft.class, projectInfoChange.getProCode());
//            projectDeliverableDraftService.deleteBatch(ProjectDeliverableDraft.class,
//                    Criteria.create().addCriterion("proCode", Operator.EQ, projectInfoChange.getProCode()));
            //修改申请单状态
            List<ProjectInfoChange> completes = projectInfoChangeService.list(ProjectInfoChange.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoChange infoChange : completes){
                if (infoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.AUDITING.getStatusCode())
                        ||infoChange.getBpmnStatus().equals(OrderStatusEnums.BpmnStatus.CREATE.getStatusCode())){
                    infoChange.setBpmnStatus("不同意");
                    projectInfoChangeService.update(infoChange);
                }
            }
            //修改草稿表的状态
            List<ProjectInfoDraft> drafts = projectInfoDraftService.list(ProjectInfoDraft.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectInfoDraft draft : drafts){
                if (draft.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())||draft.getIsAuditEnd()==null){
                    draft.setIsAuditEnd(CommonEnums.YesNo.YES.getCode());
                    projectInfoDraftService.update(draft);
                }
            }
            //修改草稿表-交付物的状态
            List<ProjectDeliverableDraft> deliverableDrafts = projectDeliverableDraftService.list(ProjectDeliverableDraft.class, Criteria.create().addCriterion("proCode", Operator.EQ, projectInfo.getProCode()));
            for (ProjectDeliverableDraft draft : deliverableDrafts){
                if (draft.getIsAuditEnd().equals(CommonEnums.YesNo.NO.getCode())||draft.getIsAuditEnd()==null){
                    draft.setIsAuditEnd(CommonEnums.YesNo.YES.getCode());
                    projectDeliverableDraftService.update(draft);
                }
            }
        }
        return Result.OK("变更失败");
    }

//    /**
//     * 计算项目进度，
//     */
//    @Override
//    @Transactional
//    public void calculateProgress() {
//        Criteria criteria = Criteria.create();
//        List<ProjectInfo> list = this.list(ProjectInfo.class, criteria);
//        for (ProjectInfo projectInfo : list) {
//            //计算项目进度
//            String proCode = projectInfo.getProCode();
//            Criteria c = Criteria.create().addCriterion("proCode", Operator.EQ, proCode);
//            List<ProjectTask> task = projectTaskService.list(ProjectTask.class, c);
//            int size = task.size();
//            if (size== 0){
//                BigDecimal zero = BigDecimal.ZERO;
//                projectInfo.setSchedule(zero);
//                this.update(projectInfo);
//                continue;
//            }
//            int finished = 0;
//            int unfinished = 0;
//            for (ProjectTask projectTask : task){
//                if (projectTask.getExecutionStatus().equals(ProjectTaskEnums.ExecutionStatus.FINISHED.getCode())){
//                    finished += 1;
//                }else{
//                    unfinished +=1;
//                    if (unfinished == size){
//                        BigDecimal zero = BigDecimal.ZERO;
//                        projectInfo.setSchedule(zero);
//                        this.update(projectInfo);
//                        continue;
//                    }
//                }
//            }
//
//            BigDecimal progress = new BigDecimal(finished).divide(new BigDecimal(size),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
//            projectInfo.setSchedule(progress);
//            this.update(projectInfo);
//        }
//
//    }

    @Override
    @Transactional
    public void deleteAll(String proCode) {
        //删除项目
        this.delete(ProjectInfo.class, proCode);
        //删除项目交付物
        List<ProjectDeliverable> list = projectDeliverableService.list(ProjectDeliverable.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        for (ProjectDeliverable projectDeliverable : list) {
            projectDeliverableService.delete(ProjectDeliverable.class, projectDeliverable.getId());
        }

        //删除项目任务
        List<ProjectTask> task = projectTaskService.list(ProjectTask.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        for (ProjectTask projectTask : task) {
            projectTaskService.delete(ProjectTask.class, projectTask.getTaskCode());

            //删除项目任务交付物
            List<ProjectTaskDeliverable> deliverable = projectTaskDeliverableService.list(ProjectTaskDeliverable.class, Criteria.create().addCriterion("taskCode", Operator.EQ, projectTask.getTaskCode()));
            for (ProjectTaskDeliverable projectTaskDeliverable : deliverable) {
                projectTaskDeliverableService.delete(projectTaskDeliverable.getId(), ProjectTaskDeliverable.class);
            }

            //删除任务问题
            List<ProjectProblem> problems = projectProblemService.list(ProjectProblem.class, Criteria.create().addCriterion("taskCode", Operator.EQ, projectTask.getTaskCode()));
            for (ProjectProblem projectProblem : problems) {
                projectProblemService.delete(projectProblem.getQuestionCode(), ProjectProblem.class);
            }
        }
        //删除项目风险
        List<ProjectDanger> dangers = projectDangerService.list(ProjectDanger.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        for (ProjectDanger projectDanger : dangers) {
            projectDangerService.delete(projectDanger.getDangerCode(), ProjectDanger.class);
        }


    }

    /**
     * 获取我负责的项目信息列表
     *
     * @param page
     * @param criteria
     * @return
     */
    @Override
    @Transactional
    public Page<ProjectInfo> listPageHead(Pageable page, Criteria criteria) {
        //项目经理
        criteria = criteria.addCriterion("proLeader", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
        Page<ProjectInfo> pageResult = this.listPage(ProjectInfo.class, page, criteria);
        return pageResult;
//        if (pageResult.getContent().size() > 0) {
//            return pageResult;
//        } else {
//            //项目秘书
//            Criteria c = Criteria.create().addCriterion("proSecretary", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
//            Page<ProjectInfo> pageResult1 = this.listPage(ProjectInfo.class, page, c);
//            return pageResult1;
//        }

    }

    /**
     * 获取我参与的项目信息列表
     *
     * @param page
     * @param criteria
     * @return
     */
    @Override
    @Transactional
    public Page<ProjectInfo> listPageJoin(Pageable page, Criteria criteria) {
        //项目经理
        criteria = criteria.addCriterion("proLeader", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
        List<ProjectInfo> list = this.list(ProjectInfo.class, criteria);
        //项目秘书
        Criteria c = Criteria.create().addCriterion("proSecretary", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
        List<ProjectInfo> list1 = this.list(ProjectInfo.class, c);
        //任务负责人
        Criteria c1 = Criteria.create().addCriterion("head", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
        List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, c1);//找到任务负责人对应的任务，提取项目编码
        List<ProjectInfo> projectInfos = new ArrayList<>();
        for (ProjectTask task : tasks) {
            ProjectInfo projectInfo = this.getById(ProjectInfo.class, task.getProCode());
            projectInfos.add(projectInfo);
        }
        //任务成员
        Criteria c2 = Criteria.create().addCriterion("taskMembers", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
        List<ProjectTask> tasks1 = projectTaskService.list(ProjectTask.class, c2);//找到任务成员对应的任务，提取项目编码
        List<ProjectInfo> projectInfos1 = new ArrayList<>();
        for (ProjectTask task : tasks1) {
            ProjectInfo projectInfo = this.getById(ProjectInfo.class, task.getProCode());
            projectInfos1.add(projectInfo);
        }
        // 合并4个结果列表
        List<ProjectInfo> combinedList = new ArrayList<>();
        combinedList.addAll(list);
        combinedList.addAll(list1);
        combinedList.addAll(projectInfos);
        combinedList.addAll(projectInfos1);

        // 使用 LinkedHashSet 进行去重，同时保持插入顺序
        Set<ProjectInfo> uniqueSet = new LinkedHashSet<>(combinedList);

        // 将去重后的 Set 转换回 List
        List<ProjectInfo> uniqueList1 = new ArrayList<>(uniqueSet);


//        Collections.sort(uniqueList, Comparator.comparing(ProjectInfo::getCreateTime).reversed());
        List<ProjectInfo> uniqueList = uniqueList1.stream()
                .filter(Objects::nonNull) // 如果需要，过滤掉 null 元素
                .sorted(Comparator.comparing(ProjectInfo::getCreateTime).reversed())
                .collect(Collectors.toList());// 降序排序


//        Collections.sort(uniqueList, Comparator.comparing(ProjectInfo::getCreateTime).reversed());

//        PageImpl<ProjectInfo> infoPage = new PageImpl<>(uniqueList, page, uniqueList.size());
//        return infoPage;
        // 假设你已经有了一个去重后的列表 uniqueList
        long totalElements = uniqueList.size(); // 总元素数
        int totalPages = (int) Math.ceil((double) totalElements / page.getPageSize()); // 计算总页数

// 计算当前页应该开始的索引
        int startIndex = page.getPageNumber() * page.getPageSize();

// 如果startIndex超过列表大小，则返回一个空的Page
        if (startIndex >= totalElements) {
            return new PageImpl<>(Collections.emptyList(), page, totalElements);
        }

// 获取当前页应该包含的元素数量
        int endIndex = (int) Math.min(startIndex + page.getPageSize(), totalElements);

// 从uniqueList中获取当前页的数据
        List<ProjectInfo> currentPageData = uniqueList.subList(startIndex, endIndex);

// 创建PageImpl实例
        PageImpl<ProjectInfo> infoPage = new PageImpl<>(currentPageData, page, totalElements);

// 返回分页数据
        return infoPage;

//        //项目经理
//        criteria = criteria.addCriterion("proLeader", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
//        Page<ProjectInfo> pageResult = this.listPage(ProjectInfo.class, page, criteria);
//        if (pageResult.getContent().size() > 0) {
//            return pageResult;
//        } else {
//            //项目秘书
//            Criteria c = Criteria.create().addCriterion("proSecretary", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
//            Page<ProjectInfo> pageResult1 = this.listPage(ProjectInfo.class, page, c);
//            if (pageResult1.getContent().size() > 0) {
//                return pageResult1;
//            } else {
//                //任务负责人
//                Criteria c1 = Criteria.create().addCriterion("head", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
//                List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, c1);//找到任务负责人对应的任务，提取项目编码
//                ArrayList<ProjectInfo> projectInfos = new ArrayList<>();
//                for (ProjectTask task : tasks) {
//                    ProjectInfo projectInfo = this.getById(ProjectInfo.class, task.getProCode());
//                    projectInfos.add(projectInfo);
//                }
//                PageImpl<ProjectInfo> infoPage = new PageImpl<>(projectInfos, page, projectInfos.size());
//                if (infoPage.getContent().size() > 0) {
//                    return infoPage;
//                } else {
//                    //任务成员
//                    Criteria c2 = Criteria.create().addCriterion("taskMembers", Operator.LIKE, "%" + SecurityUtils.getLoginUsername() + "%");
//                    List<ProjectTask> tasks1 = projectTaskService.list(ProjectTask.class, c2);//找到任务成员对应的任务，提取项目编码
//                    ArrayList<ProjectInfo> projectInfos1 = new ArrayList<>();
//                    for (ProjectTask task : tasks1) {
//                        ProjectInfo projectInfo = this.getById(ProjectInfo.class, task.getProCode());
//                        projectInfos1.add(projectInfo);
//                    }
//                    PageImpl<ProjectInfo> infoPage1 = new PageImpl<>(projectInfos1, page, projectInfos1.size());
//                    return infoPage1;
//                }
//            }
//        }
    }

    /**
     * 根据模版新增项目
     *
     * @param templateCode
     * @return
     */
    @Override
    @Transactional
    public Result<?> add(String templateCode) {
        //添加项目信息
        ProjectInfoTemplate infoTemplate = projectInfoTemplateService.getById(ProjectInfoTemplate.class, templateCode);
        if (infoTemplate == null) {
            return Result.error("模板不存在");
        }
        ProjectInfo projectInfo = new ProjectInfo();
        BeanUtil.copyProperties(infoTemplate, projectInfo, "proCode");
        projectInfo.setProStatus(PlmEnums.ProStatus.NEW.getCode());
//        projectInfo.setOverdueDay(0);
        projectInfo.setStatus("1");
        this.save(projectInfo);

        Criteria criteria = Criteria.create().addCriterion("templateCode", Operator.EQ, templateCode);
        //添加项目交付物
        List<ProjectDeliverableTemplate> list = projectDeliverableTemplateService.list(ProjectDeliverableTemplate.class, criteria);
        if (list != null && list.size() > 0) {
            for (ProjectDeliverableTemplate template : list) {
                ProjectDeliverable projectDeliverable = new ProjectDeliverable();
                BeanUtil.copyProperties(template, projectDeliverable, "docNO", "proCode");
                projectDeliverable.setProCode(projectInfo.getProCode());
                projectDeliverableService.save(projectDeliverable);
            }
        }
        //添加项目任务
        List<ProjectTaskTemplate> list1 = projectTaskTemplateService.list(ProjectTaskTemplate.class, criteria);
//        ProjectTask projectTask = new ProjectTask();
        if (list1 != null && list1.size() > 0) {
            for (ProjectTaskTemplate template : list1) {
                String taskCode = template.getTaskCode();//模版任务的编码
                ProjectTask projectTask = new ProjectTask();
                BeanUtil.copyProperties(template, projectTask, "taskCode", "proCode");

                //处理任务成员、负责人
                projectTask.setTaskMembers(dealUserName(template.getTaskMembers()));
                projectTask.setHead(dealUserName(template.getHead()));

                projectTask.setProCode(projectInfo.getProCode());
                projectTask.setTaskStatus("1");
                projectTask.setExecutionStatus("10");
                //添加任务对应的项目名称和状态和项目经理
                projectTask.setProName(projectInfo.getProName());
                projectTask.setProStatus(projectInfo.getProStatus());
                projectTask.setProLeader(projectInfo.getProLeader());
                projectTask.setTaskTemplateCode(taskCode);
                projectTaskService.save(projectTask);
                //将父级编码进行更换
                if(projectTask.getParentTaskCode()!=null){
                    List<ProjectTask> list11 = JpaUtil.linq(ProjectTask.class).equal("taskTemplateCode", projectTask.getParentTaskCode()).list();
                    for (ProjectTask one : list11){
                        if(one.getProCode().equals(projectTask.getProCode())){
                            projectTask.setParentTaskCode(one.getTaskCode());
                            projectTaskService.update(projectTask);
                        }
                    }
                }
                //添加项目任务交付物
                //查询对应的任务交付物模版

                List<ProjectTaskDeliverableTemplate> taskDeliverableTemplates = projectTaskDeliverableTemplateService.list(ProjectTaskDeliverableTemplate.class, Criteria.create().addCriterion("taskCode", Operator.EQ, taskCode));
                if (taskDeliverableTemplates != null && taskDeliverableTemplates.size() > 0) {
                    for (ProjectTaskDeliverableTemplate template1 : taskDeliverableTemplates) {
                        ProjectTaskDeliverable projectTaskDeliverable = new ProjectTaskDeliverable();
                        BeanUtil.copyProperties(template1, projectTaskDeliverable, "docNO", "taskCode");
                        projectTaskDeliverable.setTaskCode(projectTask.getTaskCode());
                        projectTaskDeliverableService.save(projectTaskDeliverable);
                    }
                }
            }
        }
//        //添加项目任务交付物
//        List<ProjectTaskDeliverableTemplate> list2 = projectTaskDeliverableTemplateService.list(ProjectTaskDeliverableTemplate.class, criteria);
//        if (list2!= null && list2.size() > 0){
//            for (ProjectTaskDeliverableTemplate template : list2) {
//                ProjectTaskDeliverable projectTaskDeliverable = new ProjectTaskDeliverable();
//                BeanUtil.copyProperties(template,projectTaskDeliverable,"docNO","taskCode");
//                projectTaskDeliverable.setTaskCode(projectTask.getTaskCode());
//                projectTaskDeliverableService.save(projectTaskDeliverable);
//            }
//        }

        return Result.OK(projectInfo);
    }

    private String dealUserName(String taskMembers){
        if(StrUtil.isEmpty(taskMembers)){
            return "";
        }
        taskMembers = StrUtil.addPrefixIfNot(taskMembers, ",");
        taskMembers = StrUtil.addSuffixIfNot(taskMembers, ",");

        return taskMembers;
    }
    /**
     * 查询当前项目下任务各个状态的任务数量
     * @param proCode
     * @return
     */
    @Override
    @Transactional
    public Result<?> getTaskNumber(String proCode) {
        ProjectInfo projectInfo = this.getById(ProjectInfo.class, proCode);
        List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        int size = tasks.size();
        projectInfo.setTaskCount(size);//任务总数
        int taskCountNew =0;//新建任务数量
        int taskCountExecute =0;//执行中任务数量
        int taskCountFinish=0;//完成任务数量
        int taskCountShutDown=0;//已关闭任务数量
//        int taskCountLate=0;//逾期任务数量
        for (ProjectTask task : tasks){
            if (task.getExecutionStatus().equals(PlmEnums.ExecutionStatus.WAIT_FOR_START.getCode())){//新增
                taskCountNew=taskCountNew+1;
            }
            if (task.getExecutionStatus().equals(PlmEnums.ExecutionStatus.EXECUTING.getCode())){//执行中
                taskCountExecute=taskCountExecute+1;
            }
            if (task.getExecutionStatus().equals(PlmEnums.ExecutionStatus.FINISHED.getCode())){//已完成
                taskCountFinish=taskCountFinish+1;
            }
            if (task.getExecutionStatus().equals(PlmEnums.ExecutionStatus.CLOSED.getCode())){//已关闭
                taskCountShutDown=taskCountShutDown+1;
            }
        }
        projectInfo.setTaskCountNew(taskCountNew);
        projectInfo.setTaskCountExecute(taskCountExecute);
        projectInfo.setTaskCountFinish(taskCountFinish);
        projectInfo.setTaskCountShutDown(taskCountShutDown);
        this.update(projectInfo);
        return Result.OK(projectInfo);
    }

    @Override
    @Transactional
    public Result<?> getProgress(String proCode) {
        ProjectInfo projectInfo = this.getById(ProjectInfo.class, proCode);
        List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        int size = tasks.size();
        projectInfo.setTaskCount(size);//当前项目任务总数
        //查找项目交付物
        List<ProjectDeliverable> list = projectDeliverableService.list(ProjectDeliverable.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        int infoDeliverableCount =0;
        for (ProjectDeliverable projectDeliverable : list){
            if (projectDeliverable.getDocFile()!=null){
                infoDeliverableCount+=1;
            }
        }
        projectInfo.setInfoDeliverableCount(infoDeliverableCount);//信息交付物数量

        //项目成员
        String infoPeoples =null;//全部成员
        String proLeader = projectInfo.getProLeader();//项目经理
        String proSecretary = projectInfo.getProSecretary();//项目秘书
        String taskPeoples=null;//全部的任务成员
        String taskHeads =null;//任务负责人
        for(ProjectTask task : tasks){
            String taskMembers = task.getTaskMembers();//任务成员
            String head = task.getHead();//任务负责人
//            Integer heads= countPersons(head);
            if(taskMembers !=null&&!taskMembers.equals("")){
                String subsTaskMembers = taskMembers.substring(1, taskMembers.length() - 1);
                String subHead = head.substring(1, head.length() - 1);
                if (taskHeads == null){
                    taskHeads = subHead;
                }else {
                    taskHeads = taskHeads +","+subHead;
                }
                if (taskPeoples ==null){
                    taskPeoples=subsTaskMembers+","+subHead;
                }else {
                    taskPeoples=taskPeoples+","+subsTaskMembers+","+subHead;
                }
            }else {
                String subHead = head.substring(1, head.length() - 1);
                if (taskHeads == null){
                    taskHeads = subHead;
                }else {
                    taskHeads = taskHeads +","+subHead;
                }
                if (taskPeoples ==null){
                    taskPeoples=subHead;
                }else {
                    taskPeoples=taskPeoples+","+subHead;
                }
            }
//


        }
        if (proSecretary!=null&& !proSecretary.equals("")){//项目秘书不为空，
            if (taskPeoples ==null){
                infoPeoples = proLeader +","+proSecretary ;
            }else {
                infoPeoples = proLeader +","+proSecretary +","+taskPeoples ;
            }

        }else {
            if (taskPeoples ==null){
                infoPeoples = proLeader  ;
            }else {
                infoPeoples = proLeader+","+ taskPeoples  ;
            }
        }
        //去重
        // 将字符串拆分为数组
        String[] peopleArray = infoPeoples.split(",");
        Set<String> uniqueTaskHead = new HashSet<>();
        if (taskHeads !=null){
            String[] taskHeadArray = taskHeads.split(",");
//            Set<String> uniqueTaskHead = new HashSet<>();
            for (String person : taskHeadArray) {
                uniqueTaskHead.add(person);
            }
        }


        // 使用HashSet来去重
        Set<String> uniquePeople = new HashSet<>();
        for (String person : peopleArray) {
            uniquePeople.add(person);
        }
//        Set<String> uniqueTaskHead = new HashSet<>();
//        for (String person : taskHeadArray) {
//            uniqueTaskHead.add(person);
//        }

        // 如果需要，将去重后的集合转回字符串
        StringBuilder uniqueInfoPeoples = new StringBuilder();
        for (String uniquePerson : uniquePeople) {
            if (uniqueInfoPeoples.length() > 0) {
                uniqueInfoPeoples.append(",");
            }
            uniqueInfoPeoples.append(uniquePerson);
        }

        StringBuilder uniqueTaskHeads = new StringBuilder();
        for (String uniquePerson : uniqueTaskHead) {
            if (uniqueTaskHeads.length() > 0) {
                uniqueTaskHeads.append(",");
            }
            uniqueTaskHeads.append(uniquePerson);
        }

        //人员个数
        String peoples = uniqueInfoPeoples.toString();
        Integer integer = countPersons(peoples);

        //任务负责人个数
        String taskHeadPeoples = uniqueTaskHeads.toString();

        if (taskHeadPeoples ==null || taskHeadPeoples.equals("")){
            Integer taskHeadss =0 ;
            projectInfo.setTaskHeads(taskHeadss);
        }else {
            Integer taskHeadss = countPersons(taskHeadPeoples);
            projectInfo.setTaskHeads(taskHeadss);
        }

        projectInfo.setInfoMember(integer);

        //计划进度
        Integer taskItShouldBeDone =0;//当天应当完成任务
        for(ProjectTask task : tasks){
            //判断任务当天是否应该计划结束
            LocalDate currentDate = LocalDate.now(); //获取当前时间
            Date planEndTime = task.getPlanEndTime();
            LocalDate planEndLocalDate = planEndTime.toInstant()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDate();
            if (currentDate.isAfter(planEndLocalDate)) {
                taskItShouldBeDone += 1;
            }
        }
        if (size ==0){
            projectInfo.setInfoPlanProgress(new BigDecimal(0));
            this.update(projectInfo);
        }else {
            BigDecimal planProgress = new BigDecimal(taskItShouldBeDone).divide(new BigDecimal(size),2,BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));
            projectInfo.setInfoPlanProgress(planProgress);
            this.update(projectInfo);
        }
        return Result.OK(projectInfo);
    }

    @Override
    @Transactional
    public Result<?> getProblemDistribution(String proCode) {
        String sql= "SELECT SERVERITY_ AS severity, COUNT(*) AS num \n" +
                "FROM MB_ERP_PLM_PROJECT_PROBLEM\n" +
                "WHERE PRO_CODE_ = '"+ proCode +"'\n" +
                "GROUP BY SERVERITY_";
        List<ProjectProblemBO> resultList = JpaUtil.nativeQuery(sql).getResultList();
        return Result.OK(resultList);
    }

    @Override
    @Transactional
    public Result<?> getDangerDistribution(String proCode) {
        String sql= "SELECT DANGER_LEVEL_, COUNT(*) \n" +
                "FROM MB_ERP_PLM_PROJECT_DANGER\n" +
                "WHERE PRO_CODE_ = '"+ proCode +"'\n" +
                "GROUP BY DANGER_LEVEL_";
        List resultList = JpaUtil.nativeQuery(sql).getResultList();
        return Result.OK(resultList);
    }

    @Override
    @Transactional
    public Result<?> getPeople(String proCode) {
        ProjectInfo projectInfo = this.getById(ProjectInfo.class, proCode);
        List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));

        //项目成员
//        String infoPeoples =null;//全部成员
//        String proLeader = projectInfo.getProLeader();//项目经理
//        String proSecretary = projectInfo.getProSecretary();//项目秘书
//        String taskPeoples=null;//全部的成员
        String taskHeadAll=null;//任务负责人总数
//        String taskMembersAll=null;//任务成员总数
        for(ProjectTask task : tasks){
//            String taskMembers = task.getTaskMembers();//任务成员
            String head = task.getHead();//任务负责人
//            Integer heads= countPersons(head);
//            String subsTaskMembers = taskMembers.substring(1, taskMembers.length() - 1);
            String subHead = head.substring(1, head.length() - 1);
            //任务负责人总数
            if (taskHeadAll ==null){
                taskHeadAll=subHead;
            }else {
                taskHeadAll=taskHeadAll+","+subHead;
            }

            //任务成员总数
//            if (taskMembersAll ==null){
//                taskMembersAll=subsTaskMembers;
//            }else {
//                taskMembersAll= taskMembersAll+","+subsTaskMembers;
//            }

//            //全部的成员
//            if (taskPeoples ==null){
//                taskPeoples=subsTaskMembers+","+subHead;
//            }else {
//                taskPeoples=taskPeoples+","+subsTaskMembers+","+subHead;
//            }

        }
//        if (proSecretary!=null){//项目秘书不为空，
//            infoPeoples = proLeader +","+proSecretary +","+taskPeoples ;
//        }else {
//            infoPeoples = proLeader+","+ taskPeoples ;
//        }
        //去重
        // 将字符串拆分为数组
//        String[] peopleArray = infoPeoples.split(",");
        String[] peopleArray = taskHeadAll.split(",");

        // 使用HashSet来去重
        Set<String> uniquePeople = new HashSet<>();
        for (String person : peopleArray) {
            uniquePeople.add(person);
        }

        // 如果需要，将去重后的集合转回字符串
        StringBuilder uniqueInfoPeoples = new StringBuilder();
        for (String uniquePerson : uniquePeople) {
            if (uniqueInfoPeoples.length() > 0) {
                uniqueInfoPeoples.append(",");
            }
            uniqueInfoPeoples.append(uniquePerson);
        }

        String string = uniqueInfoPeoples.toString();


//        Integer headCount = 0;//负责的任务数量
//        Integer finishCount = 0;//完成任务数量
//        Integer onTimeCount = 0;//按时完成任务数量
//        Integer executeCount = 0;//执行中任务数量
//        Integer toBeStartedCount = 0;//待启动任务数量
//        Integer joinCount = 0;
//        Integer problemCount = 0;
        // 将字符串拆分为数组
        String[] peoples = string.split(",");
        ArrayList<ProjectPeopleVO> projectPeopleVOS = new ArrayList<ProjectPeopleVO>();
        for (String person : peoples){
            Integer headCount = 0;//负责的任务数量
            Integer finishCount = 0;//完成任务数量
            Integer onTimeCount = 0;//按时完成任务数量
            Integer executeCount = 0;//执行中任务数量
            Integer toBeStartedCount = 0;//待启动任务数量
            ProjectPeopleVO projectPeopleVO = new ProjectPeopleVO();
            projectPeopleVO.setName(person);
            //当前人员负责任务数
            Criteria criteria = Criteria.create().addCriterion("head", Operator.LIKE, "%," + person + ",%");
            criteria.addCriterion("proCode", Operator.EQ,proCode );
            List<ProjectTask> tasks1 = projectTaskService.list(ProjectTask.class, criteria);
            headCount = tasks1.size();//负责的任务数量
            //已完成任务数量
            for(ProjectTask projectTask : tasks1){
                if(projectTask.getExecutionStatus().equals(PlmEnums.ExecutionStatus.FINISHED.getCode())){
                    finishCount +=1;
                    //按时完成任务数量
                    if (projectTask.getTaskStatus().equals("1")){
                        onTimeCount +=1;
                    }
                }
                //执行中任务数量
                if (projectTask.getExecutionStatus().equals(PlmEnums.ExecutionStatus.EXECUTING.getCode())){
                    executeCount +=1;
                }
                //待启动任务数量
                if (projectTask.getExecutionStatus().equals(PlmEnums.ExecutionStatus.WAIT_FOR_START.getCode())){
                    toBeStartedCount +=1;
                }
            }
            projectPeopleVO.setHeadTasks(headCount);
            projectPeopleVO.setFinishTasks(finishCount);
            projectPeopleVO.setOnTimeTasks(onTimeCount);
            projectPeopleVO.setExecuteTasks(executeCount);
            projectPeopleVO.setToBeStartedTasks(toBeStartedCount);
            projectPeopleVOS.add(projectPeopleVO);

            // 将字符串拆分为数组
//            String[] taskHeadAlls = taskHeadAll.split(",");
//            for (String person1 : taskHeadAlls){
//                if (person1.equals(person)){
//                    headCount+=1;
//                }
//            }

//            //当前人员参与任务数
//            // 将字符串拆分为数组
//            String[] taskMembersAlls = taskMembersAll.split(",");
//            for (String person2 : taskMembersAlls){
//                if (person2.equals(person)){
//                    joinCount+=1;
//                }
//            }

//            //当前人员负责问题数
//            List<ProjectProblem> list = projectProblemService.list(ProjectProblem.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
//            String questionLeaders = null;
//            if (list.size()>0){
//            for (ProjectProblem projectProblem : list){
//                String questionLeader = projectProblem.getQuestionLeader();
//                if (questionLeaders ==null){
//                    questionLeaders=questionLeader;
//                }else {
//                    questionLeaders=taskHeadAll+","+questionLeader;
//                }
//            }
//            String[] questionPeoples = questionLeaders.split(",");
//            for (String person3 : questionPeoples){
//                if (person3.equals(person)){
//                    problemCount+=1;
//                }
//            }
//                projectPeopleVO.setHeadQuestions(problemCount);
//        }
//            projectPeopleVO.setHeadTasks(headCount);
//            projectPeopleVO.setJoinTasks(joinCount);
//            projectPeopleVOS.add(projectPeopleVO);

        }
        return Result.OK(projectPeopleVOS);
    }

    @Override
    @Transactional
    public Result<?> getPeopleTime(String proCode) {
        List<ProjectTaskMembersTime> list = projectTaskMembersTimeService.list(ProjectTaskMembersTime.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        // 使用Map来按name分组并累加时间
        Map<String, ProjectPeopletime> groupedByName = new HashMap<>();
        for (ProjectTaskMembersTime ptmt : list) {
            String name = ptmt.getName();
            ProjectPeopletime total = groupedByName.computeIfAbsent(name, k -> new ProjectPeopletime(k, BigDecimal.ZERO, BigDecimal.ZERO));
            total.setNormalWorkTime(total.getNormalWorkTime().add(ptmt.getNormalWorkTime()));
            total.setOvertimeWorkTime(total.getOvertimeWorkTime().add(ptmt.getOvertimeWorkTime()));
        }

        // 将Map的values转换为List<ProjectTaskMembersTime>
        List<ProjectPeopletime> totalList = new ArrayList<>(groupedByName.values());

        return Result.OK(totalList);
    }

    @Override
    @Transactional
    public Result<?> getPeoplePosition(String proCode) {
        ProjectInfo projectInfo = this.getById(ProjectInfo.class, proCode);
        List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));

        //项目成员
        String infoPeoples =null;//全部成员
        String proLeader = projectInfo.getProLeader();//项目经理
        String proSecretary = projectInfo.getProSecretary();//项目秘书
        String taskPeoples=null;//全部的任务成员
        String taskHeads =null;//任务负责人
        String taskmembers= null;//任务成员
        for(ProjectTask task : tasks){
            String taskMembers = task.getTaskMembers();//任务成员
            String head = task.getHead();//任务负责人
//            Integer heads= countPersons(head);
            if(taskMembers !=null&&!taskMembers.equals("")){
                String subsTaskMembers = taskMembers.substring(1, taskMembers.length() - 1);
                String subHead = head.substring(1, head.length() - 1);
                //任务负责人
                if (taskHeads == null){
                    taskHeads = subHead;
                }else {
                    taskHeads = taskHeads +","+subHead;
                }
                //任务成员
                if (taskmembers == null){
                    taskmembers = subsTaskMembers;
                }else {
                    taskmembers = taskmembers +","+subsTaskMembers;
                }
                //全部的任务成员
                if (taskPeoples ==null){
                    taskPeoples=subsTaskMembers+","+subHead;
                }else {
                    taskPeoples=taskPeoples+","+subsTaskMembers+","+subHead;
                }
            }else {
                String subHead = head.substring(1, head.length() - 1);
                if (taskHeads == null){
                    taskHeads = subHead;
                }else {
                    taskHeads = taskHeads +","+subHead;
                }
                if (taskPeoples ==null){
                    taskPeoples=subHead;
                }else {
                    taskPeoples=taskPeoples+","+subHead;
                }
            }
//


        }
        if (proSecretary!=null&& !proSecretary.equals("")){//项目秘书不为空，
            if (taskPeoples ==null){
                infoPeoples = proLeader +","+proSecretary ;
            }else {
                infoPeoples = proLeader +","+proSecretary +","+taskPeoples ;
            }

        }else {
            if (taskPeoples ==null){
                infoPeoples = proLeader  ;
            }else {
                infoPeoples = proLeader+","+ taskPeoples  ;
            }
        }
        //去重
        // 将字符串拆分为数组
        String[] peopleArray = infoPeoples.split(",");
        Set<String> uniqueTaskHead = new HashSet<>();
        if (taskHeads !=null){
            String[] taskHeadArray = taskHeads.split(",");
//            Set<String> uniqueTaskHead = new HashSet<>();
            for (String person : taskHeadArray) {
                uniqueTaskHead.add(person);
            }
        }
        Set<String> uniqueTaskmember = new HashSet<>();
        if (taskmembers !=null &&!taskmembers.equals("")){
            String[] taskmembersArray = taskmembers.split(",");
            for (String person : taskmembersArray) {
                uniqueTaskmember.add(person);
            }
        }
        // 使用HashSet来去重
        Set<String> uniquePeople = new HashSet<>();
        for (String person : peopleArray) {
            uniquePeople.add(person);
        }
//        Set<String> uniqueTaskHead = new HashSet<>();
//        for (String person : taskHeadArray) {
//            uniqueTaskHead.add(person);
//        }


        // 如果需要，将去重后的集合转回字符串
        StringBuilder uniqueInfoPeoples = new StringBuilder();
        for (String uniquePerson : uniquePeople) {
            if (uniqueInfoPeoples.length() > 0) {
                uniqueInfoPeoples.append(",");
            }
            uniqueInfoPeoples.append(uniquePerson);
        }

        //任务负责人
        StringBuilder uniqueTaskHeads = new StringBuilder();
        for (String uniquePerson : uniqueTaskHead) {
            if (uniqueTaskHeads.length() > 0) {
                uniqueTaskHeads.append(",");
            }
            uniqueTaskHeads.append(uniquePerson);
        }
        //任务成员
        StringBuilder uniqueTaskmembers = new StringBuilder();
        for (String uniquePerson : uniqueTaskmember) {
            if (uniqueTaskmembers.length() > 0) {
                uniqueTaskmembers.append(",");
            }
            uniqueTaskmembers.append(uniquePerson);
        }

        //人员个数
        String peoples = uniqueInfoPeoples.toString();//所有成员
        String taskHeadsString = uniqueTaskHeads.toString();//任务负责人
        String taskmembersString = uniqueTaskmembers.toString();//任务成员

        // 将字符串拆分为数组
        List<ProjectinfoPeopleVO> projectinfoPeopleVOS = new ArrayList<>();
        String[] members = peoples.split(",");
        for (String user :members){
            ProjectinfoPeopleVO projectinfoPeopleVO = new ProjectinfoPeopleVO();
            projectinfoPeopleVO.setName(user);
            String position = null;
            //项目经理
            if (proLeader.contains(user)){
                position = "项目经理";
            }
            //项目秘书
            if (proSecretary.contains(user)){
                if (position ==null){
                    position = "项目秘书";
                }else {
                    position = position+","+"项目秘书";
                }
            }
            //任务负责人
            if (taskHeadsString.contains(user)){
                if (position ==null){
                    position = "任务负责人";
                }else {
                    position = position+","+"任务负责人";
                }
            }
            //任务成员
            if (taskmembersString.contains(user)){
                if (position ==null){
                    position = "任务成员";
                }else {
                    position = position+","+"任务成员";
                }
            }
            projectinfoPeopleVO.setPosition(position);
            projectinfoPeopleVOS.add(projectinfoPeopleVO);
        }
        return Result.OK(projectinfoPeopleVOS);
    }

    @Override
    @Transactional
    public Result<?> getChildDeliverable(String proCode, Pageable page,Criteria criteria) {
        ArrayList<ProjectTaskDeliverableAll> projectTaskDeliverableAlls = new ArrayList<>();
        List<Object> criterions = criteria.getCriterions();
        if (!criterions.isEmpty()){
            List<ProjectTaskDeliverable> list = projectTaskDeliverableService.list(ProjectTaskDeliverable.class, criteria);
            for (ProjectTaskDeliverable projectTaskDeliverable : list){
                ProjectTaskDeliverableAll projectTaskDeliverableAll = new ProjectTaskDeliverableAll();
                BeanUtil.copyProperties(projectTaskDeliverable,projectTaskDeliverableAll);
                projectTaskDeliverableAll.setTaskCode(projectTaskDeliverable.getTaskCode());
                ProjectTask byId = projectTaskService.getById(ProjectTask.class, projectTaskDeliverable.getTaskCode());
                projectTaskDeliverableAll.setTaskName(byId.getTaskName());
                projectTaskDeliverableAlls.add(projectTaskDeliverableAll);
            }
            PageImpl<ProjectTaskDeliverableAll> projectTaskDeliverableAlls1 = new PageImpl<>(projectTaskDeliverableAlls, page, projectTaskDeliverableAlls.size());
            return Result.OK(projectTaskDeliverableAlls1);
        }
        List<ProjectTask> tasks = projectTaskService.list(ProjectTask.class, Criteria.create().addCriterion("proCode", Operator.EQ, proCode));
        for (ProjectTask task : tasks){
            List<ProjectTaskDeliverable> taskDeliverables = projectTaskDeliverableService.list(ProjectTaskDeliverable.class, Criteria.create().addCriterion("taskCode", Operator.EQ, task.getTaskCode()));
            for (ProjectTaskDeliverable taskDeliverable : taskDeliverables){
                ProjectTaskDeliverableAll projectTaskDeliverableAll = new ProjectTaskDeliverableAll();
                BeanUtil.copyProperties(taskDeliverable,projectTaskDeliverableAll);
                projectTaskDeliverableAll.setTaskName(task.getTaskName());
                projectTaskDeliverableAll.setTaskCode(task.getTaskCode());
                projectTaskDeliverableAlls.add(projectTaskDeliverableAll);
            }
        }
        PageImpl<ProjectTaskDeliverableAll> projectTaskDeliverableAlls1 = new PageImpl<>(projectTaskDeliverableAlls, page, projectTaskDeliverableAlls.size());

        return Result.OK(projectTaskDeliverableAlls1);
    }

    @Override
    @Transactional
    public List<String> getchildren(Dept dept) {
        List<String> deptCodes = new ArrayList<>();
        List<Dept> deptList = JpaUtil.linq(Dept.class).equal("faDeptId", dept.getId()).list();
        if (deptList != null && deptList.size() > 0) {
            for (Dept dept1 : deptList) {
                deptCodes.add(dept1.getDeptCode());
                deptCodes.addAll(getchildren(dept1));
            }
        }
        return deptCodes;
    }

    /**
     * 统计成员数量
     * @param peopleName
     * @return
     */
    private Integer countPersons(String peopleName) {
        if (peopleName.contains(",")){
            return peopleName.split(",").length;
        }
        return 1;
    }



}



    /**
//     * 新增项目信息
//     * @param projectInfo
//     */
//    @Override
//    @Transactional
//    public void savePro(ProjectInfo projectInfo) {
//        this.save(projectInfo);//保存项目信息到项目表
////        List<ProjectDeliverable> projectDeliverable = projectInfo.getProjectDeliverable();
////        if (projectDeliverable != null && projectDeliverable.size() > 0){
////            saveProjectDeliverables(projectDeliverable,projectInfo.getProCode());
////        }
//    }
//
//    /**
//     * 更新项目信息
//     * @param projectInfo
//     */
//    @Override
//    @Transactional
//    public void updatePro(ProjectInfo projectInfo) {
//        this.update(projectInfo);//更新项目信息
//        List<ProjectDeliverable> projectDeliverable = projectInfo.getProjectDeliverable();
//        if (projectDeliverable != null && projectDeliverable.size() > 0){
//            updateProjectDeliverable(projectDeliverable,projectInfo.getProCode());//更新项目交付物
//        }
//    }
//
//    /**
//     *  保存项目交付物
//     * @param projectDeliverable
//     * @param proCode
//     */
//    private void saveProjectDeliverables(List<ProjectDeliverable> projectDeliverable,String proCode){
//        ProjectDeliverable bean = new ProjectDeliverable();//创建一个新的交付物
//        for (ProjectDeliverable deliverable : projectDeliverable) {//遍历交付物列表,将信息存在交付物表中
//            bean.setProCode(proCode);
//            bean.setDocNO(deliverable.getDocNO());
//            bean.setDocName(deliverable.getDocName());
//            bean.setDocType(deliverable.getDocType());
//            bean.setNumber(deliverable.getNumber());
//            bean.setDocTemp(deliverable.getDocTemp());
//            projectDeliverableService.save(bean);//保存交付物信息到交付物表
//
//        }
//    }
//
//    /**
//     * 更新项目交付物
//     * @param projectDeliverable
//     * @param proCode
//     */
//    private void updateProjectDeliverable(List<ProjectDeliverable> projectDeliverable , String proCode){
//        for(ProjectDeliverable deliverable : projectDeliverable){//对更改的交付物信息进行遍历
//            if (deliverable.getCrudType().name().equals("SAVE")){//当为新增交付物时
//                ProjectDeliverable bean = new ProjectDeliverable();
//                bean.setProCode(proCode);
//                bean.setDocNO(deliverable.getDocNO());
//                bean.setDocName(deliverable.getDocName());
//                bean.setDocType(deliverable.getDocType());
//                bean.setNumber(deliverable.getNumber());
//                bean.setDocTemp(deliverable.getDocTemp());
//                projectDeliverableService.save(bean);//保存交付物信息到交付物表
//            } else if (deliverable.getCrudType().name().equals("UPDATE")) {//当为更新时
//                projectDeliverableService.update(deliverable);
//            } else if (deliverable.getCrudType().name().equals("DELETE")) {//当为删除
//                projectDeliverableService.delete(ProjectDeliverable.class,deliverable.getDocNO());
//            }
//        }
//    }

